--[[

     Multicolor Awesome WM theme 2.0
     github.com/lcpz

--]]

local gears                                     = require("gears")
local lain                                      = require("lain")
local awful                                     = require("awful")
local wibox                                     = require("wibox")
local naughty                                   = require("naughty")
local dpi                                       = require("beautiful.xresources").apply_dpi
local utf8                                      = require("lua-utf8")

local os                                        = os
local my_table                                  = awful.util.table or gears.table -- 4.{0,1} compatibility

local theme                                     = {}
theme.confdir                                   = os.getenv("HOME") .. "/.config/awesome/themes/multicolor"
theme.wallpaper                                 = theme.confdir .. "/wall.png"
-- theme.font                                      = "sim 11"
-- theme.font                                      = "JetBrainsMono Nerd Font Mono 11"
-- theme.font                                      = "MesloLGM Nerd Font Mono 11"
-- theme.font                                      = "JetBrainsMonoNL NF 11"
theme.font                                      = "Symbols Nerd Font, JetBrainsMono Nerd Font Mono 11"
theme.menu_bg_normal                            = "#000000a0"
theme.menu_bg_focus                             = "#000000f0"
theme.bg_normal                                 = "#000000a0"
theme.bg_focus                                  = "#000000a9"
theme.bg_urgent                                 = "#000000e0"
theme.fg_normal                                 = "#aaaaaa"
theme.fg_focus                                  = "#ff8c00"
theme.fg_urgent                                 = "#af1d18"
theme.fg_minimize                               = "#ffffff"
theme.border_width                              = dpi(1)
theme.border_normal                             = "#1c2022"
theme.border_focus                              = "#a0a0a0"
theme.border_marked                             = "#3ca4d8"
theme.menu_border_width                         = dpi(1)
theme.menu_width                                = dpi(130)
theme.menu_submenu_icon                         = theme.confdir .. "/icons/submenu.png"
theme.menu_fg_normal                            = "#aaaaaaea"
theme.menu_fg_focus                             = "#ff8c00d0"
theme.menu_bg_normal                            = "#050505b0"
theme.menu_bg_focus                             = "#050505c0"
theme.taglist_squares_sel                       = theme.confdir .. "/icons/square_a.png"
theme.taglist_squares_unsel                     = theme.confdir .. "/icons/square_b.png"
theme.tasklist_plain_task_name                  = true
theme.tasklist_disable_icon                     = true
theme.useless_gap                               = 0.02
theme.layout_tile                               = theme.confdir .. "/icons/tile.png"
theme.layout_tilegaps                           = theme.confdir .. "/icons/tilegaps.png"
theme.layout_tileleft                           = theme.confdir .. "/icons/tileleft.png"
theme.layout_tilebottom                         = theme.confdir .. "/icons/tilebottom.png"
theme.layout_tiletop                            = theme.confdir .. "/icons/tiletop.png"
theme.layout_fairv                              = theme.confdir .. "/icons/fairv.png"
theme.layout_fairh                              = theme.confdir .. "/icons/fairh.png"
theme.layout_spiral                             = theme.confdir .. "/icons/spiral.png"
theme.layout_dwindle                            = theme.confdir .. "/icons/dwindle.png"
theme.layout_max                                = theme.confdir .. "/icons/max.png"
theme.layout_fullscreen                         = theme.confdir .. "/icons/fullscreen.png"
theme.layout_magnifier                          = theme.confdir .. "/icons/magnifier.png"
theme.layout_floating                           = theme.confdir .. "/icons/floating.png"
theme.titlebar_close_button_normal              = theme.confdir .. "/icons/titlebar/close_normal.png"
theme.titlebar_close_button_focus               = theme.confdir .. "/icons/titlebar/close_focus.png"
theme.titlebar_minimize_button_normal           = theme.confdir .. "/icons/titlebar/minimize_normal.png"
theme.titlebar_minimize_button_focus            = theme.confdir .. "/icons/titlebar/minimize_focus.png"
theme.titlebar_ontop_button_normal_inactive     = theme.confdir .. "/icons/titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive      = theme.confdir .. "/icons/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active       = theme.confdir .. "/icons/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active        = theme.confdir .. "/icons/titlebar/ontop_focus_active.png"
theme.titlebar_sticky_button_normal_inactive    = theme.confdir .. "/icons/titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive     = theme.confdir .. "/icons/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active      = theme.confdir .. "/icons/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active       = theme.confdir .. "/icons/titlebar/sticky_focus_active.png"
theme.titlebar_floating_button_normal_inactive  = theme.confdir .. "/icons/titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive   = theme.confdir .. "/icons/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active    = theme.confdir .. "/icons/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active     = theme.confdir .. "/icons/titlebar/floating_focus_active.png"
theme.titlebar_maximized_button_normal_inactive = theme.confdir .. "/icons/titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive  = theme.confdir .. "/icons/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active   = theme.confdir .. "/icons/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active    = theme.confdir .. "/icons/titlebar/maximized_focus_active.png"
theme.temperature                               = "°"
theme.fan                                       = utf8.char(0xf0210)
-- theme.temperature                               = utf8.char(0xf0504)

local markup                                    = lain.util.markup

-- Textclock
os.setlocale(os.getenv("LANG")) -- to localize the clock
local clockicon = wibox.widget.textbox(markup("#A9F9A9", utf8.char(0xf00f0)) .. " ")
clockicon.font = theme.font
local mytextclock = wibox.widget.textclock(
    markup("#A9F9A9", "%Y年%m月%d日%A") ..
    markup("#EAEA8C", " %I:%M") .. markup("#e33a6e", ":%S") .. markup("#EAEA8C", "%p"), 1) -- 每秒刷新一次
mytextclock.font = theme.font

-- {{{ 日历（Ccalendar）>>> 定义开始( the start of defination )  --<<中国日历>>
-- require ccal
local calendar_offset = { cur_offset = 0 } -- define date offset

local function calendar_hide()
    if not cal_notification then
        calendar_offset.cur_offset = 0
        return
    end
    naughty.destroy(cal_notification)
    cal_notification = nil
end

local function calendar_show(t_out, offset)
    calendar_hide()
    offset                     = offset or 0
    local month                = tonumber(os.date('%m'))
    local year                 = tonumber(os.date('%Y'))

    calendar_offset.cur_offset = calendar_offset.cur_offset + offset
    month                      = month + calendar_offset.cur_offset

    if month > 12 then
        month = month % 12
        year = year + 1
        if month <= 0 then
            month = 12
        end
    elseif month < 1 then
        month = month + 12
        year = year - 1
        if month <= 0 then
            month = 1
        end
    end

    -- 根据实际查询年月取得日历项
    local f = io.popen("ccal -u " ..
        month ..
        " " ..
        year ..
        "|sed \"s/\\\\[7m/<span color=\\'#a42d00\\' background=\\'#99ff99\\'>/g\" |sed \"s/\\\\[0m/<\\/span>/g\"")

    if not f then
        return
    end

    local getCalendar = "<tt><span font='WenQuanYi Zen Hei Mono 12' color='#eee'><b>"
        .. f:read() .. "</b>\n<span background='#000000a0'>"
        .. f:read() .. "</span>\n"
        .. f:read("*a"):gsub("\n*$", "")
        .. "</span></tt>"
    f:close()

    cal_notification = naughty.notify({
        text     = getCalendar,
        position = "top_right",
        fg       = "#ffeeeee",
        bg       = "#003333a9",
        timeout  = t_out
    })
end

local function calendar_attach(widget)
    widget:connect_signal("mouse::enter", function() calendar_show(0) end)
    widget:connect_signal("mouse::leave", function() calendar_hide() end)
    widget:buttons(awful.util.table.join(awful.button({}, 1, function() calendar_show(0, -1) end),
        awful.button({}, 3, function() calendar_show(0, 1) end),
        awful.button({}, 4, function() calendar_show(0, -1) end),
        awful.button({}, 5, function() calendar_show(0, 1) end)))
end
calendar_attach(mytextclock)
-- 日历（CCalendar）定义结束（end）<<< }}}

-- Weather
local weathericon = wibox.widget.textbox(markup("#eca4c4", utf8.char(0xf0909) .. " "))
weathericon.font = theme.font
local weather = lain.widget.qweather({
    city_id = '101280603', --'101070201', --Dalian      -- 1819609 ShenZhen, -- placeholder (London)
    lang = 'zh',
    APPID = '03813be948a14c6e8e641010687a74e4',
    notification_preset = { font = theme.font, fg = theme.fg_normal },
    weather_na_markup = markup.fontfg(theme.font, "#eca4c4", "N/A "),
    settings = function()
        -- io.write(string.format("test: %s", weather.icon_path))
        widget:set_markup(
            markup.fontfg("qweather 11", "#eca4c4", utf8.char(tonumber('0xf0' .. icon))) ..
            markup.fontfg(theme.font, "#eca4c4", weather_text) .. " ")
    end
})

-- Mail IMAP check
--[[ commented because it needs to be set before use
local mailicon = wibox.widget.imagebox()
theme.mail = lain.widget.imap({
    timeout  = 180,
    server   = "server",
    mail     = "mail",
    password = "keyring get mail",
    settings = function()
        if mailcount > 0 then
            mailicon:set_image(theme.widget_mail)
            widget:set_markup(markup.fontfg(theme.font, "#cccccc", mailcount .. " "))
        else
            widget:set_text("")
            --mailicon:set_image() -- not working in 4.0
            mailicon._private.image = nil
            mailicon:emit_signal("widget::redraw_needed")
            mailicon:emit_signal("widget::layout_changed")
        end
    end
})
--]]

-- CPU
local cpuicon = wibox.widget.textbox(markup("#e33a6e", utf8.char(0xf0ee0) .. " "))
cpuicon.font = theme.font
local cpu = lain.widget.cpu({
    settings = function()
        widget:set_markup(markup.fontfg(theme.font, "#e33a6e", cpu_now.usage .. "% "))
    end
})

-- Coretemp
local tempicon = wibox.widget.textbox(markup("#f1af5f", " " .. utf8.char(0xf2c9) .. " "))
tempicon.font = theme.font
local temp = lain.widget.temp({
    settings = function()
        widget:set_markup(markup.fontfg(theme.font, "#f1af5f", coretemp_now .. " L:" .. liquid_temp .. theme.temperature .. " G:" .. gpu_temp .. theme.temperature .. " "))
    end
})

-- Core fan
local fanicon = wibox.widget.textbox(markup("#87a151", theme.fan .. " "))
fanicon.font = theme.font

local fan = lain.widget.fan({
    settings = function()
        widget:set_markup(markup.fontfg(theme.font, "#87a151", pump_load .. "% " .. fan_load .. "% "))
    end
})

-- Battery
local baticon = wibox.widget.textbox(markup(theme.fg_normal, utf8.char(0xf06a5) .. " "))
baticon.font = theme.font
local bat = wibox.widget.textbox(markup(theme.fg_normal, "AC "))
bat.font = theme.font

-- ALSA volume
local volicon = wibox.widget.textbox(markup("#7493d2", " " .. utf8.char(0xf057e) .. " "))
volicon.font = theme.font
theme.volume = lain.widget.alsa({
    settings = function()
        if volume_now.level == nil then
            widget:set_markup(markup.fontfg(theme.font, "#7493d2", "err! "))
        else
            if volume_now.status == "off" then
                widget:set_markup(
                    markup.fontfg(
                        theme.font,
                        "#7493d2",
                        volume_now.level .. "%"
                    ) .. markup.fontfg(
                        theme.font,
                        "#e54c62",
                        "M "
                    )
                )
            else
                widget:set_markup(markup.fontfg(theme.font, "#7493d2", volume_now.level .. "% "))
            end
        end
    end
})

-- Net
local netdownicon = wibox.widget.textbox(markup("#87af5f", " " .. utf8.char(0xf06f4) .. " "))
netdownicon.font = theme.font
local netdowninfo = wibox.widget.textbox()
local netupicon = wibox.widget.textbox(markup("#e54c62", " " .. utf8.char(0xf06f6) .. " "))
netupicon.font = theme.font
local netupinfo = lain.widget.net({
    settings = function()
        if iface ~= "network off" and
            string.match(weather.widget.text, "N/A")
        then
            weather.update()
        end
        widget:set_markup(
            markup.fontfg(theme.font, "#e54c62",
                tonumber(net_now.sent) > 1024 and (string.format('%.2f', (tonumber(net_now.sent) / 1024)) .. 'M ') or
                (net_now.sent .. 'K ')), 0.5)
        netdowninfo:set_markup(
            markup.fontfg(theme.font, "#87af5f",
                tonumber(net_now.received) > 1024 and
                (string.format('%.2f', (tonumber(net_now.received) / 1024)) .. 'M ') or
                (net_now.received .. 'K ')), 0.5)
    end
})

-- MEM
local memicon = wibox.widget.textbox(markup("#e0da37", utf8.char(0xf035b) .. " "))
memicon.font = theme.font
local memory = lain.widget.mem({
    settings = function()
        widget:set_markup(markup.fontfg(theme.font, "#e0da37", mem_now.used .. "M "))
    end
})

-- MPD
-- local mpdicon = wibox.widget.textbox(markup("#e0da37", utf8.char(0xf0960) .. " "))
-- mpdicon.font = theme.font
-- theme.mpd = lain.widget.mpd({
--     settings = function()
--         mpd_notification_preset = {
--             text = string.format("%s [%s] - %s\n%s", mpd_now.artist,
--                 mpd_now.album, mpd_now.date, mpd_now.title)
--         }
--
--         if mpd_now.state == "play" then
--             artist = mpd_now.artist .. " > "
--             title  = mpd_now.title .. " "
--             mpdicon:set_image(theme.widget_note_on)
--         elseif mpd_now.state == "pause" then
--             artist = "mpd "
--             title  = "paused "
--         else
--             artist                 = ""
--             title                  = ""
--             --mpdicon:set_image() -- not working in 4.0
--             mpdicon._private.image = nil
--             mpdicon:emit_signal("widget::redraw_needed")
--             mpdicon:emit_signal("widget::layout_changed")
--         end
--         widget:set_markup(markup.fontfg(theme.font, "#e54c62", artist) .. markup.fontfg(theme.font, "#b2b2b2", title))
--     end
-- })

function theme.at_screen_connect(s)
    -- Quake application
    s.quake = lain.util.quake({ app = awful.util.terminal })

    -- If wallpaper is a function, call it with the screen
    local wallpaper = theme.wallpaper
    if type(wallpaper) == "function" then
        wallpaper = wallpaper(s)
    end
    gears.wallpaper.maximized(wallpaper, s, true)

    -- Tags
    awful.tag(awful.util.tagnames, s, awful.layout.layouts)

    -- Create a promptbox for each screen
    s.mypromptbox = awful.widget.prompt()
    -- Create an imagebox widget which will contains an icon indicating which layout we're using.
    -- We need one layoutbox per screen.
    s.mylayoutbox = awful.widget.layoutbox(s)
    s.mylayoutbox:buttons(my_table.join(
                           awful.button({}, 1, function () awful.layout.inc( 1) end),
                           awful.button({}, 2, function () awful.layout.set( awful.layout.layouts[1] ) end),
                           awful.button({}, 3, function () awful.layout.inc(-1) end),
                           awful.button({}, 4, function () awful.layout.inc( 1) end),
                           awful.button({}, 5, function () awful.layout.inc(-1) end)))
    -- Create a taglist widget
    s.mytaglist = awful.widget.taglist(s, awful.widget.taglist.filter.all, awful.util.taglist_buttons)

    -- Create a tasklist widget
    s.mytasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, awful.util.tasklist_buttons)

    -- Create the wibox
    s.mywibox = awful.wibar({ position = "top", screen = s, height = dpi(19), bg = theme.bg_normal, fg = theme.fg_normal })

    -- Add widgets to the wibox
    s.mywibox:setup {
        layout = wibox.layout.align.horizontal,
        { -- Left widgets
            layout = wibox.layout.fixed.horizontal,
            --s.mylayoutbox,
            s.mytaglist,
            s.mypromptbox,
        },
        --s.mytasklist, -- Middle widget
        nil,
        { -- Right widgets
            layout = wibox.layout.fixed.horizontal,
            wibox.widget.systray(),
            --mailicon,
            --theme.mail.widget,
            netdownicon,
            netdowninfo,
            netupicon,
            netupinfo.widget,
            volicon,
            theme.volume.widget,
            memicon,
            memory.widget,
            cpuicon,
            cpu.widget,
            --fsicon,
            --theme.fs.widget,
            weathericon,
            weather.widget,
            tempicon,
            temp.widget,
            fanicon,
            fan.widget,
            baticon,
            bat,
            clockicon,
            mytextclock,
        },
    }

    -- Create the bottom wibox
    s.mybottomwibox = awful.wibar({ position = "bottom", screen = s, border_width = 0, height = dpi(20), bg = theme.bg_normal, fg = theme.fg_normal })

    -- Add widgets to the bottom wibox
    s.mybottomwibox:setup {
        layout = wibox.layout.align.horizontal,
        { -- Left widgets
            layout = wibox.layout.fixed.horizontal,
        },
        s.mytasklist, -- Middle widget
        { -- Right widgets
            layout = wibox.layout.fixed.horizontal,
            s.mylayoutbox,
        },
    }
end

return theme
